const path = require("path");
const { nodeResolve  } = require('@rollup/plugin-node-resolve')
const commonjs = require("rollup-plugin-commonjs"); // commonjs模块转换插件
const ts = require("rollup-plugin-typescript2");
const { getBabelOutputPlugin } = require('@rollup/plugin-babel')
const rollup = require('rollup')
const getPath = (_path) => path.resolve(__dirname, _path);
const packageJSON = require("./package.json");
const babel = require("rollup-plugin-babel");
const extensions = [".js", ".ts", ".tsx"];
const babelConfig = require('./babel.config')
const globals = {
}
const umdPlugin = babel({
  exclude: "node_modules/**",
  babelrc:false,
  extensions,
  runtimeHelpers: true,
});
const babelPlugin = getBabelOutputPlugin({
  ...babelConfig
});
// ts
const tsPlugin = ts({
  tsconfig: getPath("./tsconfig.json"), // 导入本地ts配置
  extensions
});
const commPlugin = [
  nodeResolve({
    extensions
  }),
  commonjs(),
  tsPlugin,
]
// 基础配置
const commonConf = {
  input: getPath("./src/index.ts"),
  external: [],
  plugins:[
    ...commPlugin
  ],
};

const umdOutput = [
  {
    file: getPath(packageJSON.umdModule), // 通用模块
    format: "umd",
    name: "<%= umdName %>",
    globals
  }
]
const outputMap = [
  {
    file: getPath(packageJSON.main), // 通用模块
    format: "esm",
    globals
  },
  {
    file: getPath(packageJSON.cjsModule), // 通用模块
    format: "cjs",
    globals
  }
]

if(process.env.NODE_ENV === 'developemnt') {
  const watcher = rollup.watch({
    ...commonConf,
    plugins: commonConf.plugins.concat(umdPlugin),
    output:umdOutput
  })
  watcher.on('event', async (event) => {
    if(event && event.code === 'END') {
      modularityBundle()
    }
  });
} else {
  /**
   * 编译umd文件，这里因为同一个babel配置的话umd模块
   * 会出现require等关键词这浏览器是无法识别的
   * 所以umd模块和其他模块分开打包
   */
 rollup.rollup({
    ...commonConf,
    plugins: commPlugin.concat(umdPlugin),
  }).then(async (bundle)=>{
   await bundle.write(umdOutput[0])
   bundle.close
 })
  modularityBundle();
}

/**
 * 编译模块化产物
 */
function modularityBundle() {
  rollup.rollup({
    ...commonConf,
    plugins: commPlugin.concat(babelPlugin),
  }).then(async (bundle)=>{
    for await (const output of outputMap) {
      await bundle.write(output)
    }
    await bundle.close()
  })
}
